package myJs.components

import japgolly.scalajs.react._
import japgolly.scalajs.react.component.Scala.BackendScope
import japgolly.scalajs.react.extra.StateSnapshot
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.myPkg.Select2Options
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.{Event, html}

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 3/11/2020
 */
object Select2MultipleInlineComponent {

  case class Props(state: StateSnapshot[List[String]], label: String, name: String, optionMap: SeqMap[String, String],
                   questionInfo: String = "", show: Boolean = true) {
    @inline def render: VdomElement = Component(this)
  }

  class Backend(bs: BackendScope[Props, Unit]) {

    private val selectRef = Ref[html.Select]

    def didMount(p: Props) = {
      selectRef.foreach { y =>

        Tool.popover
        val jq = $(y)
        val bv = $("#form").bv
        val curJq = $(y)
        bv.addField(curJq).updateStatus(curJq, "VALID")
        if (p.show) {
          bv.revalidateField(curJq)
        } else {
          bv.updateStatus(curJq, "VALID")
        }
        val data = p.optionMap.map { case (id, text) =>
          js.Dictionary("id" -> id, "text" -> text)
        }.toJSArray
        val options = Select2Options(data = data, multiple = true, placeholder = messages("clickToChoose"))
        jq.select2(options)
        jq.select2Val(p.state.value.toJSArray)
        jq.on("select2:select select2:unselect", (e: Event) => {
          val vs = $(y).select2Val.toList
          p.state.modState { x =>
            vs
          }.unsafeRunSync()
        })

      }
    }

    def didUpdate(p: Props) = {
      selectRef.foreach { y =>
        val jq = $(y)

        val data = p.optionMap.map { case (id, text) =>
          js.Dictionary("id" -> id, "text" -> text)
        }.toJSArray
        val options = Select2Options(data = data, multiple = true, placeholder = messages("clickToChoose"))
        jq.mySelect2(options)
        jq.select2Val(p.state.value.toJSArray)

        val bv = $("#form").bv
        if (p.show) {
          bv.revalidateField(jq)
        } else {
          bv.updateStatus(jq, "VALID")
        }
      }
    }

    def unmount = {
      selectRef.foreach { y =>
        val bv = $("#form").bv
        val curJq = $(y)
        bv.updateStatus(curJq, "VALID").removeField(curJq)
      }
    }

    def render(p: Props) = {

      val s = p.state.value
      div(`class` := "form-group", (display := "none").unless(p.show),
        label(`class` := "control-label col-sm-2",
          s"${p.label}", span(`class` := "",
            a(`type` := "button", `class` := "selfQuestion", title := messages("note"), VdomAttr("data-container") := "body",
              VdomAttr("data-toggle") := "popover", VdomAttr("data-html") := "true",
              VdomAttr("data-placement") := "left",
              VdomAttr("data-content") := p.questionInfo,
              VdomAttr("data-trigger") := "click",
              i(`class` := "fa fa-question-circle-o")
            ),
          ).when(p.questionInfo.nonBlank), ":"
        ),
        div(`class` := "col-sm-4",
          select(`class` := "form-control", name := s"${p.name}", value := s"${s}", width := "100%",
          ).withRef(selectRef)
        )

      )

    }

  }

  val Component = ScalaComponent.builder[Props].renderBackend[Backend].
    componentDidMount(x => x.backend.didMount(x.props)).componentWillUnmount(_.backend.unmount).
    componentDidUpdate(x => x.backend.didUpdate(x.currentProps)).
    build

}



